package com.wss.lsl.test.driven.learning.date20210808;

import java.io.File;
import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * 打印目录层次
 * 
 * @author weiss
 *
 */
public class PrintDirLevel {

	private static class Item {
		private String prefix;

		private String fileName;

		public Item(String prefix, String fileName) {
			super();
			this.prefix = prefix;
			this.fileName = fileName;
		}

		public String getPrefix() {
			return prefix;
		}

		public String getFileName() {
			return fileName;
		}
	}

	public static void print(File dir) {

		String prefix = "";
		Queue<Item> queue = new LinkedBlockingQueue<>();
		enqueue(prefix, dir, queue);

		// 打印
		while (!queue.isEmpty()) {
			Item item = queue.poll();
			System.out.print(item.getPrefix());
			System.out.println(item.getFileName());
		}
	}

	private static void enqueue(String prefix, File dir, Queue<Item> queue) {
		queue.offer(new Item(prefix, dir.getName()));
		if (dir.isFile()) {
			return;
		}
		String nextPrefix = new StringBuilder(prefix).append(" ").toString();
		for (File file : dir.listFiles()) {
			enqueue(nextPrefix, file, queue);
		}
	}
}
